package com.start.oss.ext;

import com.start.common.exceptions.StartBusException;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.core.io.Resource;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Path;

public class ByteMultipartFile implements MultipartFile {

    private final byte[] bytes;
    private final String fileName;
    private String contentType;

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public ByteMultipartFile(byte[] bytes, String fileName) {
        this.bytes = bytes;
        if (StringUtils.isEmpty(fileName)) {
            fileName = "";
        }
        this.fileName = fileName;
        this.contentType = fileName.contains(".") ? fileName.split("\\.")[1] : "";
    }

    @Override
    public String getName() {
        return fileName;
    }

    @Override
    public String getOriginalFilename() {
        return fileName;
    }

    ///
    @Override
    public String getContentType() {
        return contentType;
    }

    @Override
    public boolean isEmpty() {
        return bytes == null || bytes.length == 0;
    }

    @Override
    public long getSize() {
        return bytes.length;
    }

    @NotNull
    @Override
    public byte[] getBytes() throws IOException {
        return bytes;
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(bytes);
    }

    @Override
    public Resource getResource() {
        return null;
    }

    @Override
    public void transferTo(Path dest) throws IOException, IllegalStateException {


    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        new FileOutputStream(dest).write(bytes);
    }

    /**
     * @param base64
     * @return
     */
    public static MultipartFile base64ToMultipart(String base64, String fileName) {
        String[] baseStrs = base64.split("base64,");
        if (StringUtils.isEmpty(fileName)) {
            String[] split = baseStrs[0].split("/");
            String fileSuffix = split[1].replace(";", "");
            fileName = System.currentTimeMillis() + "." + fileSuffix;
        }
        byte[] decode = Base64Utils.decodeFromString(baseStrs[1]);
        return byteToMultipart(decode, fileName);
    }

    public static MultipartFile byteToMultipart(byte[] bytes, String fileName) {
        if (bytes == null || bytes.length < 1) throw new StartBusException("bytes is null or bytes length < 1");
        if (StringUtils.isEmpty(fileName)) throw new StartBusException("文件名称不能为空");
        return new ByteMultipartFile(bytes, fileName);
    }

}
